<template>
  <div class="order-detail-container">
    <div class="order-detail-card">
      <!-- 返回按钮 -->
      <div class="back-button" @click="goToHome">
        <el-icon class="back-icon"><ArrowLeftBold /></el-icon>
        <span>返回</span>
      </div>

      <!-- 顶部状态区域 -->
      <div class="status-section">
        <div class="success-icon">
          <el-icon class="icon"><CircleCheckFilled /></el-icon>
          <div class="success-text">{{ orderDetail.buyer_pay_amount === '0.00' ? '预约成功' : '支付成功' }}</div>
          <div class="status-desc">{{ orderDetail.buyer_pay_amount === '0.00' ? '您已成功预约此课程' : '您已成功支付该订单' }}</div>
        </div>

        <div class="amount-section">
          <div class="amount-label">{{ orderDetail.buyer_pay_amount === '0.00' ? '课程价格' : '支付金额' }}</div>
          <div class="amount">￥{{ orderDetail.buyer_pay_amount }}</div>
        </div>
      </div>

      <div class="divider"></div>
      
      <!-- 订单信息区域 -->
      <div class="order-info">
        <div class="info-group">
          <div class="group-header">
            <el-icon><Document /></el-icon>
            <span>订单信息</span>
          </div>
          <div class="info-content">
            <div class="info-item">
              <span class="label">订单号</span>
              <span class="value">{{ orderDetail.out_trade_no }}</span>
            </div>
            <div class="info-item">
              <span class="label">交易号</span>
              <span class="value">{{ orderDetail.trade_no }}</span>
            </div>
            <div class="info-item">
              <span class="label">支付账号</span>
              <span class="value">{{ orderDetail.buyer_logon_id }}</span>
            </div>
            <div class="info-item">
              <span class="label">支付时间</span>
              <span class="value">{{ formatDate(orderDetail.send_pay_date) }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 倒计时提示 -->
      <div class="countdown-tip">
        {{ countdownSeconds }}秒后自动返回首页
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  CircleCheckFilled, 
  Document,
  ArrowLeftBold
} from '@element-plus/icons-vue'
import { queryPayStatus, sendOrdersPaySuccessMessage } from '@/api/order'

const route = useRoute()
const router = useRouter()

const orderDetail = ref({
  out_trade_no: '',
  trade_no: '',
  buyer_logon_id: '',
  buyer_pay_amount: '',
  send_pay_date: ''
})

// 倒计时相关
const countdownSeconds = ref(60) // 1分钟 = 60秒
let timer = null

// 开始倒计时
const startCountdown = () => {
  timer = setInterval(() => {
    if (countdownSeconds.value > 0) {
      countdownSeconds.value--
    } else {
      clearInterval(timer)
      goToHome()
    }
  }, 1000)
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  const second = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`
}

const getOrderDetail = async () => {
  try {
    // 先检查localStorage中是否有订单数据
    const orderDetailDataStr = localStorage.getItem('orderDetailData')
    if (orderDetailDataStr) {
      // 如果存在，使用localStorage中的数据
      const orderDetailData = JSON.parse(orderDetailDataStr)
      orderDetail.value = {
        out_trade_no: orderDetailData.ordersId,
        trade_no: orderDetailData.transactionId,
        buyer_logon_id: '免费课程',
        buyer_pay_amount: orderDetailData.paymentAmount || '0.00',
        send_pay_date: orderDetailData.createTime
      }
      
      // 使用完后删除localStorage中的数据
      localStorage.removeItem('orderDetailData')
      return
    }
    
    // 如果localStorage中没有数据，继续原有逻辑
    const orderId = route.query.orderId
    if (!orderId) {
      ElMessage.error('订单号不存在')
      router.push('/home')
      return
    }

    const response = await queryPayStatus(orderId)
    console.log('订单详情响应:', response)

    if (response.code === 200) {
      // 解析支付宝返回的交易信息
      const alipayResponse = response.data.response ? JSON.parse(response.data.response) : null
      const alipayTradeResponse = alipayResponse?.alipay_trade_query_response
      
      if (alipayTradeResponse) {
        orderDetail.value = {
          out_trade_no: alipayTradeResponse.out_trade_no || response.data.out_trade_no,
          trade_no: alipayTradeResponse.trade_no || response.data.trade_no,
          buyer_logon_id: alipayTradeResponse.buyer_logon_id,
          buyer_pay_amount: alipayTradeResponse.buyer_pay_amount || response.data.total_amount,
          send_pay_date: alipayTradeResponse.send_pay_date || response.data.gmt_payment
        }
      } else {
        // 如果没有支付宝响应数据，使用后端返回的数据
        orderDetail.value = {
          out_trade_no: response.data.out_trade_no,
          trade_no: response.data.trade_no,
          buyer_logon_id: response.data.buyer_id,
          buyer_pay_amount: response.data.total_amount,
          send_pay_date: response.data.gmt_payment
        }
      }
    } else {
      ElMessage.error('获取订单详情失败:' + response.message)
      setTimeout(() => {
        router.push('/home')
      }, 2000)
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败，请重试')
    setTimeout(() => {
      router.push('/home')
    }, 2000)
  }
}

const goToHome = () => {
  router.push('/home')
}

const sendPaySuccessMessage = async () => {
  try {
    const res = await sendOrdersPaySuccessMessage(route.query.orderId)
    if (!res.success) {
      console.error('发送订单支付成功消息失败:', res.message)
    }
  } catch (error) {
    console.error('发送订单支付成功消息失败:', error)
  }
}

onMounted(() => {
  getOrderDetail()
  startCountdown()
  if (route.query.orderId) {
    sendPaySuccessMessage()
  }
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style scoped>
.order-detail-container {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 40px 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.order-detail-card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  padding: 40px;
  width: 100%;
  max-width: 560px;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}

.back-button {
  position: absolute;
  top: 20px;
  left: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  color: #606266;
  transition: all 0.3s ease;
  padding: 6px 12px;
  border-radius: 4px;
  background-color: #f4f4f5;
  z-index: 1;
}

.back-button:hover {
  background-color: #e9e9eb;
  color: #409EFF;
}

.back-icon {
  font-size: 16px;
}

.status-section {
  width: 100%;
  text-align: center;
  margin-bottom: 32px;
}

.success-icon {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 24px;
}

.success-icon .icon {
  font-size: 64px;
  color: #67c23a;
  margin-bottom: 16px;
}

.success-text {
  font-size: 24px;
  color: #67c23a;
  font-weight: 500;
  margin-bottom: 8px;
}

.status-desc {
  color: #909399;
  font-size: 14px;
}

.amount-section {
  text-align: center;
  margin-top: 24px;
}

.amount-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.amount {
  font-size: 36px;
  font-weight: 600;
  color: #303133;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.divider {
  width: 100%;
  height: 1px;
  background: #ebeef5;
  margin: 32px 0;
}

.order-info {
  width: 100%;
  margin-bottom: 24px;
}

.info-group {
  background: #f8f9fa;
  border-radius: 12px;
  overflow: hidden;
}

.group-header {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 16px 24px;
  background: #f0f2f5;
  color: #303133;
  font-weight: 500;
}

.group-header .el-icon {
  font-size: 18px;
}

.info-content {
  padding: 16px 24px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  font-size: 14px;
}

.info-item:not(:last-child) {
  border-bottom: 1px dashed #ebeef5;
}

.info-item .label {
  color: #909399;
}

.info-item .value {
  color: #303133;
  font-weight: 500;
}

.countdown-tip {
  color: #909399;
  font-size: 14px;
  margin-top: 24px;
  text-align: center;
}

@media (max-width: 768px) {
  .order-detail-container {
    padding: 20px 16px;
  }

  .order-detail-card {
    padding: 24px;
  }

  .success-icon .icon {
    font-size: 48px;
  }

  .success-text {
    font-size: 20px;
  }

  .amount {
    font-size: 32px;
  }

  .info-group {
    border-radius: 8px;
  }

  .group-header {
    padding: 12px 16px;
  }

  .info-content {
    padding: 12px 16px;
  }
}
</style> 